package com.block.job.service.channelcost;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.constant.RedisKeyConstant;
import com.block.db.entity.ChannelCountInfo;
import com.block.db.entity.SystemConstantInfo;
import com.block.db.mapper.ChannelCountInfoMapper;
import com.block.db.mapper.SystemConstantInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ChannelVivoCostService {

    public static String getAccountInfoUrl = "https://marketing-api.vivo.com.cn/openapi/v1/account/fetch/account?advertiser_id={}&nonce={}&access_token={}&timestamp={}";

    public static String CODE_VIVO_TOKEN = "VIVO_TOKEN_CODE";

    public static String CLIENT_ID = "20240716015";

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Resource
    SystemConstantInfoMapper systemConstantInfoMapper;
    @Autowired
    TransactionTemplate transactionTemplate;
    @Resource
    ChannelCountInfoMapper channelCountInfoMapper;

    public void getAccountCost(){

        String accessToken = getToken();
        String timestamp = System.currentTimeMillis()+"";// todo
        String advertiserId = "33b753773a30c7066b2b";// todo
        String nonce = UUID.randomUUID().toString().replaceAll("-","");

        String requestUrl = StrUtil.format(getAccountInfoUrl, advertiserId, nonce, accessToken, timestamp);

        String result = HttpUtil.createGet(requestUrl).execute().body();

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        if (code == 0){

            JSONObject data = resultObject.getJSONObject("data");
            BigDecimal dailyExpend = data.getBigDecimal("dailyExpend");
            BigDecimal costAmount =  dailyExpend.divide(new BigDecimal(100000));

            transactionTemplate.execute(new TransactionCallback<Object>() {
                @Override
                public Object doInTransaction(TransactionStatus status) {

                    String dateInfo = LocalDate.now().toString();
                    ChannelCountInfo channelCountInfo = channelCountInfoMapper.getEntityByChannelCodeAndDateInfo("vivo", dateInfo);
                    if (ObjectUtil.isNotEmpty(channelCountInfo)){
                        ChannelCountInfo updateEntity = new ChannelCountInfo();
                        updateEntity.setId(channelCountInfo.getId());
                        updateEntity.setUvCost(costAmount);
                        channelCountInfoMapper.updateById(updateEntity);
                    }
                    return null;
                }
            });
        }
        return;
    }

    public String getToken() {
        String redisKey = StrUtil.format(RedisKeyConstant.VIVO_CHANNEL_ACCESS_TOKEN, CLIENT_ID);
        String token = stringRedisTemplate.opsForValue().get(redisKey);
        if (StrUtil.isNotEmpty(token)) {
            return token;
        }

        // 为空，或者超时，则触发刷新操作
        SystemConstantInfo tokenInfo = systemConstantInfoMapper.getEntityByCode(CODE_VIVO_TOKEN);
        if (ObjectUtil.isNotEmpty(tokenInfo)){
            // 更新access token 缓存信息
            stringRedisTemplate.opsForValue().set(redisKey, tokenInfo.getContentInfo(), 7, TimeUnit.DAYS);
            return tokenInfo.getContentInfo();
        }
        return null;
    }

}
